import * as util from '@/util'
import router from '@/router/'

export default {
  state: {
    user: util.getUser(),
    token: util.getToken()
  },
  mutations: {
    setToken (state, token) {
      state.token = token
      util.setToken(token)
    },
    removeToken (state) {
      state.token = ''
      util.removeToken()
    },
    setUser (state, user) {
      state.user = user
      util.setUser(user)
    },
    removeUser (state) {
      state.user = null
      util.removeUser()
    }
  },
  actions: {
    // 登录
    handleLogin ({ commit }, { UserName, Password }) {
      UserName = UserName.trim()
      return new Promise((resolve, reject) => {
        http.post(api.Login, {
          UserName,
          Password
        }).then(res => {
          commit('setToken', res.Data)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut ({ state, commit }) {
      return new Promise((resolve, reject) => {
        api.logout().then(res => {
          commit('removeToken')
          commit('removeStaticObject')
          commit('clearAppCache')

          router.push({
            name: 'login'
          })
        }).catch(err => {
          reject(err)
        })
      })
    }
  }
}
